<?php

// +----------------------------------------------------------------------
// | yogurt
// +----------------------------------------------------------------------
// +----------------------------------------------------------------------
// | Author: fengyi <1719847255.qq.com>
// +----------------------------------------------------------------------

namespace yogurt;

/**
 * 配置文件类
 * Class Config
 * @package yogurt
 */
class Config
{
    /**
     * 配置项属性
     * @var array
     */
    private static $config = [];

    /**
     * 根据配置文件名获取配置
     * @param string $key
     * @return mixed
     * @throws Exception
     */
    public static function get($key = '')
    {
        if (empty($key)) {
            return self::getAllConfig();
        }
        
        if (strpos($key, '.') === false) {
            $configArr = Builder::includeFile(CONFIG_PATH . $key . PHP_SUFFIX);
            if (isset(self::$config[$key])) {
                $configArr = array_merge($configArr, self::$config[$key]);
            }
            return $configArr;
        }
        $keyArr = explode('.', $key);
        if (isset($keyArr[1]) && !empty($keyArr[1]) && isset(self::$config[$keyArr[0]][$keyArr[1]])) {
            return self::$config[$keyArr[0]][$keyArr[1]];
        }
        $configArr = Builder::includeFile(CONFIG_PATH . $keyArr[0] . PHP_SUFFIX);
        if (isset($keyArr[1]) && !empty($keyArr[1])) {
            return $configArr[$keyArr[1]];
        }
        return array_merge($configArr, self::$config[$keyArr[0]] ?? []);
    }

    /**
     * 获取所有配置项
     * @return array
     * @throws Exception
     */
    private static function getAllConfig(): array
    {
        $handle = opendir(CONFIG_PATH);
        $files = [];
        while (($filename = readdir($handle)) !== false) {
            // 务必使用!==，防止目录下出现类似文件名“0”等情况
            if ($filename !== "." && $filename !== "..") {
                $files[] = $filename;
            }
        }
        closedir($handle);
        $config = [];
        // 打印所有文件名
        foreach ($files as $value) {
            $keyArr = explode('.', $value);
            $config[$keyArr[0]] = self::get($keyArr[0]);
        }
        return $config;
    }

    /**
     * 设置配置项
     * @param $key
     * @param array $value
     * @return bool
     */
    public static function set($key, $value = []): bool
    {
        if (empty($value) || is_null($key)) {
            return false;
        }
        if (empty(self::$config) || !isset(self::$config[$key])) {
            self::$config[$key] = $value;
        } else {
            self::$config[$key] = array_merge(self::$config[$key], $value);
        }
        return true;
    }
}
